<script>
	import {
		mapState, 
		mapMutations
	} from 'vuex'
	import Vue from 'vue'
	import socket from './tool/socketCon.js'
	export default {
		data() {
			return {

			}
		},
		// provide() {
		// 	return {
		// 		initSocket: () => this.init(),
		// 	}
		// },
		onLaunch: function() {
			console.log(uni)
			uni.getSystemInfo({
				success: (res) => {
					this.$store.commit('setPhoneInfo', res)
				}
			})
			this.openChatDB()
			this.$getUserInfo()
			let timerId = setInterval(() => {
				if (this.$socket) {
					clearInterval(timerId)
					this.$socket.on('privateMsg_SystemToUser', data => {
						console.log('全局接收器', data)
						//告知服务器客户端收到了消息
						this.$socket.emit('MSG_OK', {
							from: data.from,
							to: data.to
						})
						//添加消息标识
						data.isSelf = 'n'
						// uni.$emit('privateMsg_SystemToUser', data)
						// #ifdef H5
						uni.$emit('privateMsg_SystemToUser', data)
						// #endif
						// 判断数据库是否打开
						// #ifdef APP-PLUS
						this.addDataToDB(data.from.senderId, data)

						// #endif

					})
					this.$socket.on('other_login', data => {
						console.log('账号在别处登录', data)
						uni.showModal({
							title: '提示',
							content: '你的账号在别处登录，如不是本人操作可能密码已泄露，请尽快修改密码',
							success: (res) => {
								uni.redirectTo({
									url: '/pages/selectPage/selectPage',
									fail: (err) => {
										console.log(err)
									}
								})
							}
						})
					})
				}
			}, 200)
		
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		onError: function(err) {
			console.log(err)

		},

		methods: {
			openChatDB() {
				this.$opChatDB.targetDataBaseOpen().then(res => {
					console.log('数据库chat是否打开', res)
					if (!res) {
						console.log('数据库chat未打开')
						this.$opChatDB.openTargetDB().then(res => {
							console.log('打开数据库chat', res.msg)
						})
					}


				})
			},

			addDataToDB(tableName, data) {
				console.log('我是否执行', tableName)
				//尝试创建表
				tableName = this.$replaceTableNameLine(tableName)
				this.$opChatDB.createTable(tableName).then(res => {
					console.log(res)
					if (res.code === 1) {
						this.$opChatDB.addData(tableName, data).then(res => {
							console.log('保存结果', res)
							if (res.code == 1) {
								console.log('已保存')
								//将接收到的消息广播到全局
								uni.$emit('privateMsg_SystemToUser', data)
								this.$opChatDB.queryLastOne(tableName).then(res => {
									console.log(`${tableName}表中的最后一条数据`, res)
								})
								// console.log(this.$opChatDB)
							}

						})


					}
				})
			},
			...mapMutations(['setUserInfo']),
		}
	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	@import "uview-ui/index.scss";
	/* #endif */

	/*每个页面公共css */
	.search-text {
		color: red;
	}
</style>
